import React, { useState, useEffect } from 'react';
import * as itemService from '../../services/itemService';
import { Card, Table, Button, Modal, Form, Input, Select, message, Upload } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, UploadOutlined } from '@ant-design/icons';

const { Option } = Select;

const Items = () => {
  const [items, setItems] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 从API获取物品数据
  useEffect(() => {
    const fetchItems = async () => {
      try {
        setLoading(true);
        const data = await itemService.getItems();
        // 直接使用API返回的数据
        const formattedItems = data.map(item => ({
          id: item.id,
          name: item.name,
          category: item.category,
          price: item.price,
          stock: item.stock,
          status: item.status,
          description: item.description
        }));
        setItems(formattedItems);
      } catch (err) {
        setError('获取物品数据失败');
        console.error('Failed to fetch items:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchItems();
  }, []);
  
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [currentItem, setCurrentItem] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [form] = Form.useForm();

  const handleAdd = () => {
    setIsAddModalOpen(true);
    form.resetFields();
  };

  const handleEdit = (item) => {
    setCurrentItem(item);
    form.setFieldsValue(item);
    setIsEditModalOpen(true);
  };

  const handleDelete = (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除此物品吗？',
      onOk: () => {
        itemService.deleteItem(id)
          .then(() => {
            setItems(items.filter(item => item.id !== id));
            message.success('删除成功');
          })
          .catch(err => {
            message.error('删除失败: ' + (err.response?.data?.error || '未知错误'));
            console.error('删除物品失败:', err);
          });
      },
    });
  };

  const handleAddOk = () => {
    form.validateFields()
      .then(values => {
        // 添加用户ID (实际应用中可能从认证系统获取)
        const itemData = {
          ...values,
          user_id: 1
        };
        itemService.addItem(itemData)
          .then(newItem => {
            // 直接使用API返回的数据
            const formattedItem = {
              id: newItem.id,
              name: newItem.name,
              category: newItem.category,
              price: newItem.price,
              stock: newItem.stock,
              status: newItem.status,
              description: newItem.description
            };
            setItems([...items, formattedItem]);
            setIsAddModalOpen(false);
            message.success('添加成功');
          })
          .catch(err => {
            message.error('添加失败: ' + (err.response?.data?.error || '未知错误'));
            console.error('添加物品失败:', err);
          });
      })
      .catch(err => {
        console.error('表单验证失败:', err);
      });
  };

  const handleEditOk = () => {
    form.validateFields()
      .then(values => {
        itemService.updateItem(currentItem.id, values)
          .then(updatedItem => {
            // 更新本地数据
            const updatedItems = items.map(item =>
              item.id === currentItem.id ? {
                ...item,
                ...values,
                price: updatedItem.price // 确保价格与API返回一致
              } : item
            );
            setItems(updatedItems);
            setIsEditModalOpen(false);
            message.success('更新成功');
          })
          .catch(err => {
            message.error('更新失败: ' + (err.response?.data?.error || '未知错误'));
            console.error('更新物品失败:', err);
          });
      })
      .catch(err => {
        console.error('表单验证失败:', err);
      });
  };

  const filteredItems = items.filter(item =>
    item.name.includes(searchText) ||
    item.category.includes(searchText) ||
    item.price.toString().includes(searchText)
  );

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '物品名称', dataIndex: 'name', key: 'name' },
    { title: '分类', dataIndex: 'category', key: 'category' },
    { title: '价格', dataIndex: 'price', key: 'price', render: price => `¥${price}` },
    { title: '库存', dataIndex: 'stock', key: 'stock' },
    { title: '状态', dataIndex: 'status', key: 'status', render: status => (
      <span style={{ color: status === '在售' ? 'green' : 'red' }}>{status}</span>
    )},
    { title: '操作', key: 'action', render: (_, record) => (
      <div>
        <Button type="primary" icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)} style={{ marginRight: 8 }}>编辑</Button>
        <Button type="danger" icon={<DeleteOutlined />} size="small" onClick={() => handleDelete(record.id)}>删除</Button>
      </div>
    )},
  ];

  return (
    <div>
      <Card title="物品管理" variant="filled" extra={<Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>添加物品</Button>}>        {loading ? (
          <div style={{ textAlign: 'center', padding: '24px' }}>加载中...</div>
        ) : error ? (
          <div style={{ textAlign: 'center', padding: '24px', color: 'red' }}>{error}</div>
        ) : (
          <>
            <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end' }}>
              <Input
                placeholder="搜索物品..."
                prefix={<SearchOutlined />}
                value={searchText}
                onChange={e => setSearchText(e.target.value)}
                style={{ width: 300 }}
              />
            </div>
            <Table columns={columns} dataSource={filteredItems} rowKey="id" />
          </>
      )}
      </Card>

      {/* 添加物品模态框 */}
      <Modal
        title="添加物品"
        open={isAddModalOpen}
        onOk={handleAddOk}
        onCancel={() => setIsAddModalOpen(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="物品名称" rules={[{ required: true, message: '请输入物品名称' }]}>
            <Input placeholder="请输入物品名称" />
          </Form.Item>
          <Form.Item name="category" label="分类" rules={[{ required: true, message: '请选择分类' }]}>
            <Select placeholder="请选择分类">
              <Option value="电子设备">电子设备</Option>
              <Option value="电脑配件">电脑配件</Option>
              <Option value="办公用品">办公用品</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          <Form.Item name="price" label="价格" rules={[{ required: true, message: '请输入价格' }, { type: 'number', min: 0, message: '价格不能为负数' }]}>
            <Input type="number" placeholder="请输入价格" />
          </Form.Item>
          <Form.Item name="stock" label="库存" rules={[{ required: true, message: '请输入库存' }, { type: 'number', min: 0, message: '库存不能为负数' }]}>
            <Input type="number" placeholder="请输入库存" />
          </Form.Item>
          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="在售">在售</Option>
              <Option value="缺货">缺货</Option>
              <Option value="下架">下架</Option>
            </Select>
          </Form.Item>
          <Form.Item name="image" label="物品图片">
            <Upload name="image" listType="picture">
              <Button icon={<UploadOutlined />}>上传图片</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>

      {/* 编辑物品模态框 */}
      <Modal
        title="编辑物品"
        open={isEditModalOpen}
        onOk={handleEditOk}
        onCancel={() => setIsEditModalOpen(false)}
        width={600}
      >
        <Form form={form} layout="vertical">
          <Form.Item name="name" label="物品名称" rules={[{ required: true, message: '请输入物品名称' }]}>
            <Input placeholder="请输入物品名称" />
          </Form.Item>
          <Form.Item name="category" label="分类" rules={[{ required: true, message: '请选择分类' }]}>
            <Select placeholder="请选择分类">
              <Option value="电子设备">电子设备</Option>
              <Option value="电脑配件">电脑配件</Option>
              <Option value="办公用品">办公用品</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>
          <Form.Item name="price" label="价格" rules={[{ required: true, message: '请输入价格' }, { type: 'number', min: 0, message: '价格不能为负数' }]}>
            <Input type="number" placeholder="请输入价格" />
          </Form.Item>
          <Form.Item name="stock" label="库存" rules={[{ required: true, message: '请输入库存' }, { type: 'number', min: 0, message: '库存不能为负数' }]}>
            <Input type="number" placeholder="请输入库存" />
          </Form.Item>
          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="在售">在售</Option>
              <Option value="缺货">缺货</Option>
              <Option value="下架">下架</Option>
            </Select>
          </Form.Item>
          <Form.Item name="image" label="物品图片">
            <Upload name="image" listType="picture">
              <Button icon={<UploadOutlined />}>上传图片</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Items;